// +----------------------------------------------------------------------
// | LikeShop100%开源免费商用电商系统
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | 商业版本务必购买商业授权，以免引起法律纠纷
// | 禁止对系统程序代码以任何目的，任何形式的再发布
// | Gitee下载：https://gitee.com/likemarket/likeshopv2
// | 访问官网：https://www.likemarket.net
// | 访问社区：https://home.likemarket.net
// | 访问手册：http://doc.likemarket.net
// | 微信公众号：好象科技
// | 好象科技开发团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | Author: LikeShopTeam
// +----------------------------------------------------------------------

<template>
	<view>
		<view class="confirm-order">
			<view class="confirm-con">
				<navigator hover-class="none" url="/pages/user_address/user_address?type=1">
					<address-item :address="address"></address-item>
				</navigator>
				<view class="goods contain">
					<order-goods :team="{need: orderInfo.team_need}" :list="goodsLists"></order-goods>
					<view class="item row-between">
						<view>配送方式</view>
						<view>快递</view>
					</view>
					<view class="item row-between">
						<view>买家留言</view>
						<u-input v-model="userRemark" class="flex1 ml20" :clearable="false" placeholder="请添加备注（150字以内）">
						</u-input>
					</view>
				</view>

				<view class="pay-way contain">
					<view class="lighter title">支付方式</view>
					<radio-group class="radio-group" @change="radioChange">
						<label v-for="(item, index) in payWayArr" :key="index" class="item row-between">
							<view class="row">
								<image class="icon-lg mr20" :src="item.icon"></image>
								<view class>
									<view class="balck bt10">{{item.name}}</view>
									<view class="muted xs">{{item.extra}}</view>
								</view>
							</view>
							<radio class="radio" :value="String(item.pay_way)" :checked="item.pay_way == payWay">
							</radio>
						</label>
					</radio-group>
				</view>
				<view class="price contain">
					<view class="item row-between">
						<view>商品金额</view>
						<view>¥{{orderInfo.total_goods_price || '0.00'}}</view>
					</view>
					<view class="item row-between">
						<view>运费</view>
						<view>¥{{orderInfo.shipping_price || '0.00'}}</view>
					</view>
					<template v-if="insurance !== null">
						<view class="item row-between">
							<view>保险套餐</view>
							<view>¥{{ insurance || '0.00' }}</view>
						</view>
					</template>
				</view>
			</view>
			<view class="footer bg-white row-between fixed">
				<view class="all-price lg row">
					<text>合计：</text>
					<view class="ornament">
						<price-format :first-size="36" :second-size="36" :price="orderInfo.order_amount"></price-format>
					</view>
				</view>
				<button class="btn br60 white" size="md" hover-class="none" @tap="onSubmitOrder">
					提交订单
				</button>
			</view>
		</view>
		<loading-view v-if="showLoading" background-color="transparent" :size="50"></loading-view>
		<loading-view v-if="isFirstLoading"></loading-view>

		<!-- 支付密码 -->
		<set-pay-pwd ref="setPayPwd" @confirm="orderBuyFun('submit', $event)" />
	</view>
</template>

<script>
	import {
		orderBuy,
		getOrderCoupon
	} from '@/api/order';
	import {
		teamBuy
	} from '@/api/activity'
	import {
		prepay,
		getMnpNotice,
		getPayway,
		getAlipayPayStatus
	} from '@/api/app';
	import {
		wxpay,
		alipay
	} from '@/utils/pay'
	export default {
		data() {
			return {
				isFirstLoading: true,
				showLoading: false,
				address: {},
				orderInfo: {},
				goodsLists: [],
				addressId: '',
				popActive: 0,
				userRemark: '',
				payWayArr: [],
				payWay: '',
				insurance: 0, // 保险套餐
			};
		},

		onLoad(options) {
			this.getPaywayFun()
			uni.$on("selectaddress", (e) => {
				this.addressId = e.id;
			})
			const data = JSON.parse(decodeURIComponent(options.data));
			this.goods = data.goods
			this.type = data.type
			this.insurance = data.insurance;
		},

		onShow: async function() {
			if (this.payStatus) return;
			setTimeout(() => {
				this.orderBuyFun();
			}, 100)
		},
		onUnload: function() {
			uni.$off("selectaddress")
		},
		methods: {
			getPaywayFun() {
				return new Promise(resolve => {
					getPayway().then(res => {
						if (res.code == 1) {
							this.payWayArr = res.data
							this.payWay = res.data.length ? res.data[0].pay_way : 0
							resolve()
						}
					})
				})
			},
			radioChange(e) {
				this.payWay = Number(e.detail.value)
			},

			getAuthMsg() {
				return new Promise(resolve => {
					getMnpNotice({
						scene: 1
					}).then(res => {
						if (res.code == 1) {
							uni.requestSubscribeMessage({
								tmplIds: res.data,

								fail(res) {
									console.log(res);
								},

								complete() {
									resolve();
								}

							});
						} else {
							resolve();
						}
					});
				});
			},

			onSubmitOrder() {
				if (!this.addressId) return this.$toast({
					title: "请选择收货地址"
				});

				uni.showModal({
					title: '温馨提示',
					content: '是否确认下单?',
					confirmColor: '#FF2C3C',
					success: async res => {
						if (!res.confirm) return;
						// #ifdef MP-WEIXIN
						await this.getAuthMsg();
						//#endif

						if (this.payWay == 3) {
							this.$refs.setPayPwd.hasPayWord().then(res => {
								this.$refs.setPayPwd.showInputPwd();
							});
						} else {
							this.orderBuyFun('submit');
						}
					}
				});
			},

			async orderBuyFun(action = 'info', password) {
				this.showLoading = true;
				let {
					address,
					userRemark,
					payWay,
				} = this;
				let submitObj = {
					action,
					goods: this.goods,
					pay_way: payWay,
					address_id: this.addressId,
					safe_package: this.insurance,
					pay_password: password
				};
				if (action == 'submit') {
					submitObj.remark = userRemark;
					submitObj.type = this.type;
					if (!this.payWayArr.length) {
						this.showLoading = false
						return this.$toast({
							title: '请联系管理员配置支付方式'
						})
					}
				}
				const {
					data: orderData,
					code: orderCode
				} = await orderBuy(submitObj)
				if (orderCode != 1) return this.showLoading = false
				if (action == 'info') {
					let {
						address,
						goods_lists
					} = orderData;
					this.address = address;
					this.addressId = address.id;
					this.goodsLists = goods_lists;
					this.orderInfo = orderData;
					this.showLoading = false;
					this.$nextTick(() => {
						this.isFirstLoading = false
					});
				} else if (action == 'submit') {
					let {
						order_id,
						type
					} = orderData;
					const {
						data: prepayData,
						code: prepayCode
					} = await prepay({
						from: type,
						order_id
					})
					this.showLoading = false
					if (prepayCode == 1) {
						wxpay(prepayData).then((res) => {
							if (res == 'success') {
								this.payStatus = true;
								uni.redirectTo({
									url: `/pages/pay_result/pay_result?id=${order_id}`
								});
							} else {
								uni.redirectTo({
									url: '/pages/user_order/user_order'
								});
							}
						})
					} else if (prepayCode == 20001) {
						// #ifdef H5
						alipay(prepayData);
						// #endif
						
						// #ifdef MP-ALIPAY
						const tradeNo = prepayData?.data?.trade_no;
						my.tradePay({
							// 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
							tradeNO: tradeNo,
							success: (res) => {
								getAlipayPayStatus({
									trade_no: tradeNo
								}).then(res => {
									if (res.tradeStatus == 'TRADE_SUCCESS') {
										uni.redirectTo({
											url: `/pages/pay_result/pay_result?id=${order_id}`
										});
									} else {
										uni.redirectTo({
											url: '/pages/user_order/user_order'
										});
									}
								});
							},
							fail: (res) => {
								uni.redirectTo({
									url: '/pages/user_order/user_order'
								});
							}
						});
						// #endif
					} else if (prepayCode == 10001) {
						//余额支付成功
						uni.redirectTo({
							url: `/pages/pay_result/pay_result?id=${order_id}`
						});
					}
				}
			}
		},


	}
</script>
<style>
	.confirm-order .confirm-con {
		overflow: hidden;
		padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
	}

	.confirm-order .contain {
		border-radius: 14rpx;
		margin: 20rpx 20rpx 0;
		background-color: #fff;
		overflow: hidden;
	}

	.confirm-order .img-line {
		height: 1.5px;
		width: 100%;
		display: block;
	}


	.confirm-order .coupons {
		height: 100rpx;
		padding: 0 24rpx;
	}

	.goods .title {
		padding: 22rpx 24rpx;
		border-bottom: 1px solid #F6F6F6;
	}

	.goods .all-num {
		padding: 22rpx 24rpx;
		border-bottom: 1px dotted #F6F6F6;
	}

	.confirm-order .footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		padding: 0 30rpx;
		box-sizing: content-box;
		padding-bottom: env(safe-area-inset-bottom);
	}


	.confirm-order .pay-way .title {
		padding: 20rpx 24rpx;
	}

	.confirm-order .pay-way .radio-group .item {
		height: 120rpx;
		padding: 0 24rpx;
	}

	.confirm-order .price {
		padding: 28rpx 20rpx;
	}

	.confirm-order .price .item:not(:last-of-type) {
		margin-bottom: 20rpx;
	}

	.confirm-order .goods>.item,
	.confirm-order .benefit>.item {
		padding: 0 24rpx;
		height: 80rpx;
	}

	.confirm-order .btn {
		/* background: linear-gradient(90deg, rgba(249, 95, 47, 1) 0%, rgba(255, 44, 60, 1) 100%); */
		background-color: #24A3FF;
		padding: 0 50rpx;
	}

	.confirm-order .van-cell:after {
		border: none;
	}

	.goods .shop-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.pop-title {
		height: 100rpx;
		border-bottom: 1rpx solid #F2F2F2;
	}

	.pop-title .title {
		margin-left: 30rpx;
		font-size: 34rpx;
		font-weight: bold;
		line-height: 36rpx;
	}
</style>
